﻿using AutoUpdate.Log;
using ScannerApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;
using Zebra.Sdk.Comm;
using Zebra.Sdk.Printer;
using Zebra.Sdk.Printer.Discovery;
using ZXing.QrCode.Internal;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace ScannerApp.Common
{
    public class ZebarPrint
    {
        public static Connection c = UsbDiscoverer.GetZebraUsbPrinters(new ZebraPrinterFilter())[0].GetConnection();

        //new DriverPrinterConnection(GetZebarPrintName());
        //UsbDiscoverer.GetZebraUsbPrinters(new ZebraPrinterFilter())[0].GetConnection();

        private static Connection GetConnection()
        {
            try
            {
                foreach (DiscoveredUsbPrinter usbPrinter in UsbDiscoverer.GetZebraUsbPrinters(new ZebraPrinterFilter()))
                {
                    //打印机连接 
                    c = usbPrinter.GetConnection();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error retrieving settings: {e.Message}");
            }
            return c;

      }
    //DriverPrinterConnection("ZDesigner ZT410-300dpi ZPL");
    //UsbDiscoverer.GetZebraUsbPrinters(new ZebraPrinterFilter())[0].GetConnection();
    //获取名称
        private static string GetZebarPrintName() {
            string name = "";
            try
            {
                foreach (DiscoveredUsbPrinter usbPrinter in UsbDiscoverer.GetZebraUsbPrinters(new ZebraPrinterFilter()))
                {
                    //打印机连接
                    name = usbPrinter.ToString();
                    // MessageBox.Show("USB:" + usbPrinter.ToString());

                }
            }
            catch(Exception ex)  { name = ex.Message; }
            return name;
        }
        //统计个数
        public static int GetZebarPrintCount()
        {
            int s = 0;
            try
            {
                foreach (DiscoveredUsbPrinter usbPrinter in UsbDiscoverer.GetZebraUsbPrinters(new ZebraPrinterFilter()))
                {
                    s++;
                }
                //if (s > 0)
                //    c.Open();

            }
            catch { }   
             return s;
        }
        //获取状态  文字 非ZPL
        public static string GetZebarPrintStatus(){
            string s = ""; 
            try
            {
                if (c.Connected)
                {
                    s = PrintStatus(c);

                }
                else
                {
                    c.Open();
                    s = PrintStatus(c);
                }
                
            }
            catch {
                
            }
            CloseConnet();
            return s;
        }
        //获取状态 代码 非ZPL
        public static string GetZebarPrintStatusCode()
        {
            string s = "";
            //foreach (DiscoveredUsbPrinter usbPrinter in UsbDiscoverer.GetZebraUsbPrinters(new ZebraPrinterFilter()))
            //{
            //    Zebra.Sdk.Comm.Connection c = usbPrinter.GetConnection();
            //    c.Open();
            try
            {
                if (c.Connected)
                {
                    s = PrintStatusCode(c);

                }
                else
                {
                    c.Open();
                    s = PrintStatusCode(c);
                }
                
            } catch {   }
            CloseConnet();
            return s;
        }
        //发送代码 utf-8
        public static string GetZebarPrintSendCode(string code)
        {
            string s = ""; 
            try
            {
                if (c.Connected)
                {

                    s = PrintSendCode(c, code);

                }
                else
                {
                    c.Open();
                    s = PrintSendCode(c, code);
                }
                
            }
            catch {
                 
            }
            CloseConnet();
            //}
            return s;
        }
        //发送代码 utf-8
        public static string GetZebarPrintSendCodeGB18030(string code)
        {
            string s = "";
            //foreach (DiscoveredUsbPrinter usbPrinter in UsbDiscoverer.GetZebraUsbPrinters(new ZebraPrinterFilter()))
            //{
            //    Zebra.Sdk.Comm.Connection c = usbPrinter.GetConnection();
            //    c.Open();
            try
            {
                if (c.Connected)
                {

                    s = PrintSendCodeGB18030(c, code);

                }
                else
                {
                    c.Open();
                    s = PrintSendCodeGB18030(c, code);
                }
            }
            catch { }
            CloseConnet();
            //}
            return s;
        }

        //关闭链接
        public static void CloseConnet()
        {
            c.Close();
        }

        /// <summary>
        /// 以下情况不会有反应
        /// Media Out (介质用尽) Ribbon Out (碳带用尽) Head Open (打印头开启)。回卷轴已满。打印头温度过高
        /// </summary>
        /// <returns></returns>
        public static string GetZebarPrintStatusZPL()
        {
            string rCode = "00",msg="";
            try
            {
                string zebraCommand = "^XA~HS^XZ";
                if (!c.Connected)
                {
                    c.Open();
                }
                //Encoding gb = Encoding.GetEncoding("GB18030");
                //byte[] gbytes = gb.GetBytes(code);
                byte[] s = c.SendAndWaitForResponse(Encoding.UTF8.GetBytes(zebraCommand), 1, 1, null);
                string s1 = Encoding.UTF8.GetString(s);
                if (s1 == "") rCode = "00";
                else
                {
                    string[] ss = Encoding.UTF8.GetString(s).Split(',');
         
                    for (int i = 0; i < ss.Length; i++)
                    {
                        msg = "接口:" + ss[0];
                        if (i == 1 && ss[i] == "1")
                        {
                            msg += ";缺纸";
                            rCode = "04";
                        }
                        else if (i == 2 && ss[i] == "1")
                        {
                            msg += ";暂停";
                            rCode = "01";
                        }
                        else if ((i == 5 || i == 6 || i == 7 || i == 9 || i == 10 || i == 11) && ss[i] == "1")
                        {
                            msg += ";其他错误";
                            rCode = "0" + i;
                        }
                    }
                }
                
            }
            catch(Exception ex) {
                msg = ex.Message;
                rCode = "99";
            }
            finally
            {
                Logger.Instance.WriteLog(publicclass.UserName + "获取打印机状态ZPL状态:" + rCode + msg, LogType.Information, "PackingZebar");

                CloseConnet();
            }
            return rCode;

        }

        /// <summary>
        /// 就绪=0,
        //卡纸=1,
        //    缺纸=2,
        //    无碳带 = 3,
        //    暂停打印 = 4,
        //    打印中 = 5,
        //    外盖开启 = 6
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        private static string PrintStatusCode(Connection connection)
        {
            string status = "",msg="";
            try
            {
                if(!connection.Connected)
                connection.Open();
                ZebraPrinter printer =  ZebraPrinterFactory.GetInstance(connection);

                PrinterStatus printerStatus = printer.GetCurrentStatus();
                if (printerStatus.isReadyToPrint)//可以打印
                {
                    status = "00";
                }
                  if (printerStatus.isPaused)//暂停
                {
                    status = "01";
                }
                  if (printerStatus.isHeadOpen)//
                {
                    status = "05";
                }
                  if (printerStatus.isPaperOut)
                {
                    status = "04";
                }
                  if (printerStatus.isHeadTooHot)
                {
                    status = "06";
                }
                  if (printerStatus.isPartialFormatInProgress)
                {
                    status = "07";
                }
                  if (printerStatus.isReceiveBufferFull)
                {
                    status = "08";
                }
                  if (printerStatus.isRibbonOut)
                {
                    status = "09";
                }
                
            }
            catch (ConnectionException ex)
            {
                // status = "99";
                msg = ex.Message;
                Console.WriteLine(ex.ToString());
            }
            catch (ZebraPrinterLanguageUnknownException ex)
            {
                msg = ex.Message;
                status = "99"; //ex.Message; 
            }
            finally
            {
                Logger.Instance.WriteLog(publicclass.UserName + "获取打印机状态:"+ status+ msg, LogType.Information, "PackingZebar");

                connection.Close();
            }
            return status;
        }
         private static string PrintStatus(Connection connection)
        {
            string status = "";
            try
            {

                connection.Open();
                ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection);

                PrinterStatus printerStatus = printer.GetCurrentStatus();
                PrinterLanguage printerLanguage = printer.PrinterControlLanguage;
                status += printerLanguage;
                if (printerStatus.isReadyToPrint)
                {
                    status = "";//isReadyToPrint
                    Console.WriteLine("Ready To Print");
                }
                  if (printerStatus.isPaused)
                {
                    status += "暂停isPaused";
                    Console.WriteLine("Cannot Print because the printer is paused.");
                }
                  if (printerStatus.isHeadOpen)
                {
                    status += "盖子打开isHeadOpen";
                    Console.WriteLine("Cannot Print because the printer head is open.");
                }
                  if (printerStatus.isPaperOut)
                {
                    status += "缺纸isPaperOut";
                    Console.WriteLine("Cannot Print because the paper is out.");
                }
                  if (printerStatus.isPartialFormatInProgress)
                {
                    status = "isPartialFormatInProgress";
                }
                  if (printerStatus.isReceiveBufferFull)
                {
                    status = "isReceiveBufferFull";
                }
                  if (printerStatus.isRibbonOut)
                {
                    status = "isRibbonOut";
                }
                 
            }
            catch (ConnectionException ex)
            {
                status = ex.Message;
                Console.WriteLine(ex.ToString());
            }
            catch (ZebraPrinterLanguageUnknownException ex)
            {
                status = ex.Message;
                Console.WriteLine(ex.ToString());
            }
            
            finally
            {
                connection.Close();
            }
            return status;
        }
     
        private static string PrintSendCodeGB18030(Connection connection,string code)
        {
            string status = "";
            try
            {

                connection.Open();
                // string code_utf8= HttpUtility.UrlEncode("字符串", Encoding.UTF8);
               // connection.Write(Encoding.UTF8.GetBytes(code));
                //ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection);
                //PrinterLanguage printerLanguage = printer.PrinterControlLanguage;
                //printer.SendCommand(code);
                Encoding gb = Encoding.GetEncoding("GB18030"); 
                byte[] gbytes = gb.GetBytes(code);
                connection.Write(gbytes);
                //System.Text.Encoding gb2312;
                //gb2312 = System.Text.Encoding.GetEncoding("gb2312");
                //byte[] b = gb2312.GetBytes(code);
                //connection.Write(Encoding.ASCII.GetBytes(code));


            }
            catch (ConnectionException ex)
            {
                status = ex.Message;
                Console.WriteLine(ex.ToString());
            }
            //catch (ZebraPrinterLanguageUnknownException ex)
            //{
            //    status = ex.Message;
            //    Console.WriteLine(ex.ToString());
            //}
            finally
            {
                Logger.Instance.WriteLog(publicclass.UserName + "ZebraZD420[打印]，命令:" + code+";状态:"+ status, LogType.Information, "PackingZebar");

                connection.Close();
            }

            return status;
        }


        private static string PrintSendCode(Connection connection, string code)
        {
            string status = "";
            try
            {

                connection.Open();
                // string code_utf8= HttpUtility.UrlEncode("字符串", Encoding.UTF8);
                connection.Write(Encoding.UTF8.GetBytes(code));
                //ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection);
                //PrinterLanguage printerLanguage = printer.PrinterControlLanguage;
                //printer.SendCommand(code);



            }
            catch (ConnectionException ex)
            {
                status = ex.Message;
                Console.WriteLine(ex.ToString());
            }
            //catch (ZebraPrinterLanguageUnknownException ex)
            //{
            //    status = ex.Message;
            //    Console.WriteLine(ex.ToString());
            //}
            finally
            {
                Logger.Instance.WriteLog(publicclass.UserName + "Zebra[打印]，命令:"+ code + ";状态:" + status, LogType.Information, "PackingZebar");

                connection.Close();
            }
            return status;
        }

        public byte[] byte_gbk2utf8(byte[] bytes)
        {
            return Encoding.Convert(Encoding.GetEncoding("GBK"), Encoding.UTF8, bytes);
        }


        //打印文件
        public static string PrintPath(string path)
        {
            string name = GetZebarPrintName();
            string flag = "";
            Connection connection = new UsbConnection(name);
            try
            {
                connection.Open();
                //c = new DriverPrinterConnection(name);
                //c.open();
                ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection);
                //"E:\\打印机测试\\123.txt"
                printer.SendFileContents(path);
                
            }
            catch (ConnectionException e)
            {
                flag = e.Message;
               // MessageBox.Show(e.ToString());
            }
            catch (ZebraPrinterLanguageUnknownException e)
            {
                flag = e.Message;
              //  MessageBox.Show(e.ToString());
            }
            finally
            {
                connection.Close();
            }
            //printer.SendFileContents("E:\\打印机测试\\123.txt");
            return flag;
        }




      

    }
}
